package com.manager.commons.utils;

import java.io.File;
import java.io.IOException;
import java.util.Date;

import org.slf4j.Logger;

import com.manager.commons.file.FileUtil;
import com.manager.commons.log.LogFactory;

public class FileUtils {

	protected static Logger logger = LogFactory.getLogger(FileUtils.class);

	/**
	 * 复制文件
	 * @param thumbnailPath
	 * @param uploadFilePath
	 * @param id
	 * @return
	 */
	public static String copyFile(String thumbnailPath, String uploadFilePath, String id) {
		if (StringUtil.isNotEmpty(thumbnailPath)) {
			String filePath = "/file/upload/";
			String fssFilePath = uploadFilePath.concat(filePath).concat(id);
			File fssFile = new File(fssFilePath);
			if (!fssFile.exists()) {
				fssFile.mkdirs();
			}
			String ymd = DateUtil.format(new Date(), "yyyyMMdd");
			String ymdFilePath = fssFilePath.concat("/").concat(ymd);
			File ymdFile = new File(ymdFilePath);
			if (!ymdFile.exists()) {
				ymdFile.mkdirs();
			}
			String fileExt = FileUtil.getFileSuffix(thumbnailPath);
			String newFileName = id + "." + fileExt;
			String newFilePath = filePath + id + "/" + ymd + "/" + newFileName;
			try {
				FileUtil.copyFile(new File(uploadFilePath + thumbnailPath), new File(ymdFilePath + "/" + newFileName));
			} catch (IOException e) {
				logger.error(e.getMessage(), e);
			}
			return newFilePath;
		}
		return thumbnailPath;
	}

	/**
	 * 复制文件
	 * @param thumbnailPath
	 * @param uploadFilePath
	 * @return
	 */
	public static String copyFileToFile(String thumbnailPath, String uploadFilePath, String filePath) {
		if (StringUtil.isNotEmpty(thumbnailPath)) {
			String newFilePath = thumbnailPath.replace("/temp/", filePath);
			try {
				String newFileName = newFilePath.substring((newFilePath.lastIndexOf("/") + 1));
				System.out.println("fileName:" + newFileName);
				String path = newFilePath.substring(0, newFilePath.indexOf(newFileName) - 1);
				System.out.println("path:" + path);
				File newFile = new File(uploadFilePath + path);
				if (!newFile.exists()) {
					newFile.mkdirs();
				}
				FileUtil.copyFile(new File(uploadFilePath + thumbnailPath), new File(uploadFilePath + newFilePath));
			} catch (IOException e) {
				e.printStackTrace();
				logger.error(e.getMessage(), e);
			}
			return newFilePath;
		}
		return thumbnailPath;
	}
}